import React from 'react'
import { View, TouchableOpacity, Text, ScrollView, Image, Modal, AsyncStorage, Alert,WebView } from 'react-native'
import { CheckBox } from 'react-native-elements'
import Icon from 'react-native-vector-icons/Ionicons';
import Platform from 'Platform'
import TImage from '../../components/TImage'
import BasePage from '../common/BasePage'
import NoticeAdView from '../common/NoticeADView'
import CommonStyles from '../../common/CommonStyles'
import Config from '../../config'
import SizeUtils from '../../common/SizeUtils'
import Constants from '../../common/Constants'
import ToastUtils from '../../common/ToastUtils'
import Popover from '../common/Popover'
import PopoverConent from '../common/PopoverConent'
import CommonViewPagerMultiShow from '../common/CommonViewPagerMultiShow'
import HeartLoveItemListView from './HeartLoveItemListView'
import HeartRequestZJMsgCountAction from '../../actions/heart/HeartRequestZJMsgCountAction'
import HeartLoveRquestSelfDataAction from '../../actions/heart/HeartLoveRquestSelfDataAction'
import HeartLoveReportLoverAction from '../../actions/heart/HeartLoveReportLoverAction';
import HeartLoveBlackLoverAction from '../../actions/heart/HeartLoveBlackLoverAction';

import ResportView from '../post/ResportView';

var love_config = [
  {
    icon: require('../../../resource/images/heart/heart_tuijian.png'),
    width: 25,
    height: 25,
    title: '推荐',
    page: Config.pages.heart_love_list
  },
  {
    icon: require('../../../resource/images/heart/heart_message.png'),
    width: 25,
    height: 25,
    title: '私信',
    page: Config.pages.heart_love_he_and_she
  },
  {
    icon: require('../../../resource/images/heart/heart_my.png'),
    width: 25,
    height: 25,
    title: '我的资料',
    page: Config.pages.heart_love_question
  }
]

var love_Botton = [
  { title: '我的资料', page: Config.pages.heart_love_find_you },
  { title: '我的消息', page: Config.pages.heart_love_find_you }
]

const titleArr = [{ name: '推荐', key: 'hot' }, { name: '男', key: 'genderman' }, { name: '女', key: 'genderwoman' }]
const jubaoArr = [{name:'举报',key:'jubao'},{name:'拉黑',key:'lahei'}]
export default class HeartLovePage extends BasePage {
  constructor(props) {
    super(props)
    // this.state.isRefreshing = false;
    this._pageWidth = SizeUtils.getWindowSize().width
    this._pageHeight = SizeUtils.getWindowSize().height - Config.paddingTop - SizeUtils.translateDesignHeightToCode(100)

    this.state.msgData = 0
    this.state.selectIndex = 0
    this.state.buttonRect = {}
    this.state.isVisible = false
    this.state.showdisclamer = true
    this.state.checked=false;
  }
  componentWillUpdate(nextProps, nextStates) {
    if(nextStates.needSucced) {
      nextStates.needSucced=false;
      Alert.alert('', "已拉黑该用户。今后该用户将不能浏览到您的信息，同时无法给您发送私信", [
        {text:'确定',onPress:()=>{}},
      ])
    }
    return true;
  }

  componentDidMount() {
    this._requestData()
    this._checkDisclamerState()
  }
  // 获取个人信息失败 跳转个人资料页填写信息
  showToUpDateLoveInfo() {
    const that = this;
    AsyncStorage.getItem("wanshan",function(errs,result){
      if (result) {
          const now = new Date();
          if ((''+now.getMonth()+now.getDate())!==result) {
            AsyncStorage.setItem('wanshan', ''+now.getMonth()+now.getDate());
            Alert.alert('', '您还没有填写个人信息', [
              { text: '去完善', onPress: () => that.gotoPage(Config.pages.heart_love_find_you) },
              {text: '取消', onPress: () => {}, style: 'cancel'},
            ]) 
        }
      }else{
        const d =new Date();
        AsyncStorage.setItem('wanshan',''+d.getMonth()+d.getDate());
        Alert.alert('', '您还没有填写个人信息', [
              { text: '去完善', onPress: () => that.gotoPage(Config.pages.heart_love_find_you) },
              {text: '取消', onPress: () => {}, style: 'cancel'},
            ]) 
      }
    });
  }
  _closePopover() {
    this.setState({ isVisible: false })
  }

  _checkDisclamerState() {
    AsyncStorage.getItem(
      'DISCLAMER1',
      function(errs, result) {
        //TODO:错误处理
        if (!errs) {
          if (result && result === '1') {
            this.setState({ showdisclamer: false })
          }
        } else {
          this.setState({ showdisclamer: true })
        }
      }.bind(this)
    )
  }

  _closeDisclamer() {
    this.setState({ showdisclamer: false })
    AsyncStorage.setItem('DISCLAMER1', '1')
  }
  _PopoverPress(key) {
    // let index = 0
    if (key === 'lahei') {
      new HeartLoveBlackLoverAction().call(this, { state:1,lover_id:this.state.selectItem.lover_id })
      // Alert.alert('', "已拉黑该用户。今后该用户将不能浏览到您的信息，同时无法给您发送私信", [
      //   {text:'确定',onPress:()=>{}},
      // ])
    }else if (key === 'jubao') {
        this.setState({
          isVisible: true,
          isBottom:false,
          buttonRect: {
            x: SizeUtils.getWindowSize().width/2,
            y: 400,
            width: 0,
            height: 45
          }
        })
        return;
    }
    if (key.type!==undefined) {
      new HeartLoveReportLoverAction().call(this, { ...key,lover_id:this.state.selectItem.lover_id })
    }
    this.setState({ isVisible: false })
  }
  _showPopover(ref,selectItem) {
    ref.measure((ox, oy, width, height, px, py) => {
      this.setState({
        isVisible: true,
        isBottom:true,
        selectItem:selectItem,
        buttonRect: {
          x: Platform.OS !== 'ios' ? px - 36 : px - 30,
          y: Platform.OS !== 'ios' ? py - 36 : py - 30,
          width: 0,
          height: 45
        }
      })
    })
  }
  _requestData() {
    new HeartRequestZJMsgCountAction().call(this, { type: 1 })
    new HeartLoveRquestSelfDataAction().call(this)
    this._viewPager && this._viewPager.doRefresh()
  }

  render() {
    var displayArea = {
      x: 0,
      y: 0,
      width: SizeUtils.getWindowSize().width,
      height: 260
    }

    const showdisclamer = this.state.showdisclamer
    return (
      <View
        style={{
          paddingTop: Config.paddingTop,
          backgroundColor: '#ffffff',
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height
        }}
      >
        {this._renderNavigationBar()}
        {this._onRenderTHeader()}
        <Popover
          isVisible={this.state.isVisible}
          fromRect={this.state.buttonRect}
          placement={this.state.isBottom?'bottom':'top'}
          isWhite={true}
          arrowSize={{ height: this.state.isBottom?10:0, width: this.state.isBottom?15:0 }}
          displayArea={displayArea}
          onClose={this._closePopover.bind(this)}
        >
          <View
            style={{
              width: this.state.isBottom?100:SizeUtils.getWindowSize().width-40,
              height: this.state.isBottom?90:260,
              justifyContent: 'center',
              alignItems: 'center',
              backgroundColor: 'transparent'
            }}
          >
              {
                !this.state.isBottom?<ResportView popoverPress={this._PopoverPress.bind(this)}/>:
                <PopoverConent titleArr={jubaoArr} popoverPress={this._PopoverPress.bind(this)} />
              } 
          </View>
        </Popover>
        {showdisclamer && this._renderDisclamer()}
      </View>
    )
  }

  _renderDisclamer() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          height: SizeUtils.getWindowSize().height,
          alignItems: 'center',
          justifyContent: 'center',
          backgroundColor: '#0002',
          position: 'absolute',
          top: 0,
          left: 0
        }}
      >
        <View 
          style={{
            width: SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(112),
            height: SizeUtils.getWindowSize().height - SizeUtils.translateDesignHeightToCode(300),
            backgroundColor:'#FFF'
          }}>
            <WebView 
              automaticallyAdjustContentInsets={true}
              scalesPageToFit={true}
              style={{flex:1}}
              source={require('../../utils/MZ.html')}
            >
            </WebView>
            <CheckBox 
                containerStyle={{backgroundColor:'transparent',borderWidth:0,padding:5}}
                textStyle={{fontSize:11}}
                title='同意此条款'
                size={8}
                onPress={()=>{this.setState({checked:!this.state.checked});}}
                checkedIcon='check-square'
                uncheckedIcon='square'
                checked={this.state.checked}
            />
            <View style={{marginBottom:10,marginTop:10,alignItems: 'center',justifyContent: 'center'}}>
              <TouchableOpacity
                disabled={!this.state.checked}
                style={{
                  height: SizeUtils.translateDesignHeightToCode(68),
                  width: SizeUtils.translateDesignWidthToCode(280),
                  alignItems: 'center',
                  justifyContent: 'center',
                  backgroundColor: '#EE3535',
                  borderRadius: SizeUtils.translateDesignWidthToCode(10)
                }}
                onPress={() => {
                  this._closeDisclamer()
                }}
              >
                <Text style={{color: '#fff',fontSize: SizeUtils.translateFontSizeToCode(32)}}>确认</Text>
              </TouchableOpacity>
            </View>
            <TouchableOpacity style={{position:'absolute',top:0,right:0,width:44,height:44,alignItems: 'center',justifyContent: 'center',}} onPress={()=>{this.goBack()}}>
                <Icon style={{}} name='ios-close' color='#000' size={34} />
            </TouchableOpacity>
        </View>
      </View>
    )
  }

  _dealEnterPage() {
    super._dealEnterPage()
    this._requestData()
  }

  _onRenderTHeader() {
    return (
      <View style={{ flexDirection: 'column', backgroundColor: '#ffffff' }}>
        {this._renderBottons()}
        {this._renderTab()}
      </View>
    )
  }

  _renderSmallPager() {
    return (
      <View style={{}}>
        <CommonViewPagerMultiShow ref={ref => (this._viewPager = ref)} type={Constants.SLIDER_TYPE.HEART_LOVE} />
      </View>
    )
  }

  _renderImage() {
    return (
      <TImage
        style={{ width: 661, height: 579 }}
        source={require('../../../resource/images/heart/love_thing_banner.png')}
      />
    )
  }

  //override
  _renderTab() {
    return (
      <View
        style={{
          flexDirection: 'row',
          justifyContent: 'space-around',
          width: SizeUtils.getWindowSize().width,
          borderTopWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#999999'
        }}
      >
        {this._getTabButton(love_config[0])}
        {this._getTabButton(love_config[1])}
        {this._getTabButton(love_config[2])}
      </View>
    )
  }

  //override
  _getTabButton(item) {
    return (
      <TouchableOpacity
        onPress={() => this._onPressPageBtn(item)}
        style={{ flexDirection: 'column', alignItems: 'center' }}
      >
        <View
          style={{
            width: SizeUtils.translateDesignWidthToCode(55),
            marginTop: SizeUtils.translateFontSizeToCode(10),
            height: SizeUtils.translateDesignWidthToCode(50),
            flexDirection: 'row',
            justifyContent: 'center',
            alignItems: 'center'
          }}
        >
          <Image
            source={item.icon}
            style={{
              width: item.width,
              height: item.height
            }}
          />
        </View>
        <Text
          style={{
            color: '#666666',
            marginTop: SizeUtils.translateFontSizeToCode(5),
            backgroundColor: '#00000000',
            textAlign: 'center',
            fontSize: SizeUtils.translateFontSizeToCode(20)
          }}
        >
          {item.title}
        </Text>
      </TouchableOpacity>
    )
  }

  _renderContent() {
    return (
      <View
        style={{
          width: SizeUtils.getWindowSize().width,
          flexDirection: 'column',
          alignItems: 'center',
          marginTop: SizeUtils.translateDesignHeightToCode(8)
        }}
      >
        {this._renderContentItems()}
      </View>
    )
  }
  _renderBottons() {
    return (
      <View>
        <HeartLoveItemListView
          ref={ref => (this._listHeart = ref)}
          myLoveData={this.state.loveData}
          isReport={true}
          showPopover={this._showPopover.bind(this)}
          onRenderHeader={this.onRenderHeader.bind(this)}
          type={titleArr[this.state.selectIndex].key}
          style={{
            paddingTop: SizeUtils.translateDesignHeightToCode(0),
            width: this._pageWidth,
            height: this._pageHeight
          }}
        />
      </View>
    )
  }
  _getSortButton(typeData, index) {
    return (
      <TouchableOpacity
        key={typeData.key}
        onPress={() => {
          if (this.state.selectIndex !== index) {
            this.setState({ selectIndex: index })
            this._listHeart && this._listHeart._chageData(typeData.key)
          }
        }}
        style={[
          {
            borderColor: '#eeeeee',
            flex: 1,
            alignItems: 'center',
            flexDirection: 'row',
            justifyContent: 'center',
            borderRightWidth: SizeUtils.translateDesignWidthToCode(3)
          }
        ]}
      >
        <Text
          style={[
            CommonStyles.secondaryText,
            {
              textAlign: 'center',
              color: index === this.state.selectIndex ? '#ee3535' : '#000',
              fontSize: SizeUtils.translateFontSizeToCode(30),
              backgroundColor: '#00000000',
              borderWidth: 0
            }
          ]}
        >
          {typeData.name}
        </Text>
        {typeData.key === 'genderman' ? (
          <TImage source={require('../../../resource/images/heart/icon_sex_f.png')} style={{ width: 34, height: 34 }} />
        ) : null}
        {typeData.key === 'genderwoman' ? (
          <TImage source={require('../../../resource/images/heart/icon_sex_m.png')} style={{ width: 34, height: 34 }} />
        ) : null}
      </TouchableOpacity>
    )
  }
  onRenderHeader() {
    return (
      <View>
        {this._renderSmallPager()}
        <View style={{ backgroundColor: '#f2f2f2', height: 10 }} />
        <NoticeAdView txt="文字广告轮播" tag={3} />
        <View style={{ backgroundColor: '#f2f2f2', height: 10 }} />
        <View
          style={{
            flexDirection: 'row',
            borderColor: '#eeeeee',
            borderBottomWidth: SizeUtils.translateDesignHeightToCode(3),
            height: SizeUtils.translateDesignHeightToCode(80),
            justifyContent: 'space-around'
          }}
        >
          {titleArr.map((item, index) => this._getSortButton(item, index))}
        </View>
      </View>
    )
    return (
      <View
        style={{
          flexDirection: 'row',
          paddingLeft: SizeUtils.translateDesignWidthToCode(30),
          paddingRight: SizeUtils.translateDesignWidthToCode(20),
          backgroundColor: '#fff',
          width: SizeUtils.getWindowSize().width,
          paddingBottom: SizeUtils.translateDesignHeightToCode(22),
          justifyContent: 'space-between',
          paddingTop: SizeUtils.translateDesignHeightToCode(22),
          alignItems: 'center',
          borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: '#eeeeee'
        }}
      >
        <View style={{ flexDirection: 'row', alignItems: 'center' }}>
          <TImage source={require('../../../resource/images/home/biaotitle.png')} style={{ width: 8, height: 30 }} />
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#333333',
              marginLeft: SizeUtils.translateDesignWidthToCode(8),
              borderWidth: 0,
              backgroundColor: '#00000000',
              fontWeight: 'bold'
            }}
          >
            {titleArr[this.state.selectIndex].name}
          </Text>
        </View>
        <TouchableOpacity ref={ref => (this._popoverbtn = ref)} onPress={this._showPopover.bind(this)}>
          <Text
            style={{
              fontSize: SizeUtils.translateFontSizeToCode(28),
              color: '#999999'
            }}
          >
            {'更多 >'}
          </Text>
        </TouchableOpacity>
      </View>
    )
  }
  _onGoMyData() {
    this.gotoPage(Config.pages.heart_love_find_you)
  }

  _onGoMyMessage() {
    if (!this.state.loveData || this.state.loveData.state != 1) {
      ToastUtils.show('你不是相亲者，请先录入相亲数据')
      return
    }
    this.gotoPage(Config.pages.heart_msg_list_page, { type: 1 })
  }

  _onPressPageBtn(item) {
    if (item.title === '我的资料') {
      this.gotoPage(Config.pages.heart_love_find_you)
      return
    }
    if (item.title === '私信') {
      this._onGoMyMessage()
      return
    }
  }
  _renderNavigationBarRightButtonContent() {
    return (
      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <TImage
          source={require('../../../resource/images/workhard/search2.png')}
          style={{ width: 34, height: 34, marginTop: 5 }}
        />
      </View>
    )
  }

  _onPressNavigationBarRightBtn() {
    this.gotoPage(Config.pages.heart_love_search_main, {
      myLoveData: this.state.loveData
    })
  }
}
